package com.uenpay.util.adapter;

import java.util.List;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

/**
 * Created by PS on 2017/3/21.
 */

public abstract class CommonAdapter<T> extends RecyclerView.Adapter<CommonViewHolder>{

    private Context mContext;
    private List<T> mData;
    private int mLayoutId;
    private LayoutInflater mInflater;

    public CommonAdapter(Context context, int layoutId, List<T> datas){
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mData = datas;
        mLayoutId = layoutId;
    }

    @Override
    public CommonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return CommonViewHolder.get(mContext, parent, mLayoutId);
    }

    @Override
    public void onBindViewHolder(CommonViewHolder holder, int position) {
        convert(holder, mData.get(position));
    }

    public void add(T t){
        mData.add(t);
        notifyItemInserted(mData.size());
    }

    public void addAll(List<T> elem) {
        mData.addAll(elem);
        notifyDataSetChanged();
    }

    public void set(T oldElem, T newElem) {
        set(mData.indexOf(oldElem), newElem);
    }

    public void set(int index, T elem) {
        mData.set(index, elem);
        notifyItemInserted(index);
    }

    public void remove(T elem) {
        mData.remove(elem);
        notifyDataSetChanged();
    }

    public void remove(int index) {
        mData.remove(index);
        notifyItemRemoved(index);
    }

    public void replaceAll(List<T> elem) {
        mData.clear();
        mData.addAll(elem);
        notifyDataSetChanged();
    }

    /** Clear data list */
    public void clear() {
        mData.clear();
        notifyDataSetChanged();
    }

    public abstract void convert(CommonViewHolder holder, T t);

    @Override
    public int getItemCount() {
        return mData.size();
    }
}
